package cn.itcast.nems.studentrecord.web.controller.b;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.bean.Page;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.PageQueryModel;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import cn.itcast.nems.common.util.NumberUtil;
import cn.itcast.nems.common.web.vo.BasePageRequest;
import cn.itcast.nems.journal.dto.JournalClazzDTO;
import cn.itcast.nems.journal.dto.JournalRenewalDTO;
import cn.itcast.nems.journal.dto.JournalRenewalModel;
import cn.itcast.nems.journal.service.JournalRenewalService;
import cn.itcast.nems.manager.util.CustomBeanUtil;
import cn.itcast.nems.studentrecord.bo.JournalClazzModel;
import cn.itcast.nems.studentrecord.bo.SearchClazzQuery;
import cn.itcast.nems.studentrecord.dao.dataobject.JournalRenewalDO;
import cn.itcast.nems.studentrecord.dao.dataobject.JournalRenewalLineDiscountDO;
import cn.itcast.nems.studentrecord.web.util.JournalRenewalWebUtil;
import cn.itcast.nems.studentrecord.web.vo.form.JournalRenewalEditVO;
import cn.itcast.nems.studentrecord.web.vo.query.JournalRenewalPageQueryVO;
import cn.itcast.nems.studentrecord.web.vo.response.JournalRenewalPageVO;
import cn.itcast.nems.studentrecord.web.vo.response.StudentRecordDiscountsVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 升级凭单
 * </p>
 *
 * @author zhouwei
 * @since 2023/11/12 3:47 PM
 **/
@RestController
@RequestMapping("/b/renewal")
@RequiredArgsConstructor
@Slf4j
public class JournalRenewalController {
    private final JournalRenewalService journalRenewalService;

    /**
     * 查询分页条件班级名称
     *
     * @param queryParam 分页参数
     * @return 班级列表(包含字段 ： 班级ID 、 班级名称)
     */
    @PostMapping("/search/clazz")
    public ResponseEntity<Page<JournalClazzDTO>> findClazzList4PageSearch(@RequestBody BasePageRequest<SearchClazzQuery> queryParam) {
        queryParam.convert(50);
        JournalClazzModel clazzModel = CustomBeanUtil.copyProperties(queryParam.getCondition(), new JournalClazzModel());
        PageQueryModel<JournalClazzModel> queryModel = new PageQueryModel<>(queryParam.getPageNumber(), queryParam.getPageSize(), clazzModel);
        Page<JournalClazzDTO> pageData = journalRenewalService.findClazzList4PageSearch(queryModel);
        return ResponseEntity.ok(pageData);
    }

    /**
     * 分页查询 升级凭单
     *
     * @param queryParam 查询条件
     * @return 分页数据
     **/
    @PostMapping(value = {"/page/list", "/page/list/my_commit", "/page/list/wait_approval", "/page/list/approved", "/page/list/all"})
    public ResponseEntity<Page<JournalRenewalPageVO>> findPageList(@RequestBody BasePageRequest<JournalRenewalPageQueryVO> queryParam) {
        queryParam.convert();
        JournalRenewalModel renewalModel = CustomBeanUtil.copyProperties(queryParam.getCondition(), new JournalRenewalModel());
        PageQueryModel<JournalRenewalModel> queryModel = new PageQueryModel<>(queryParam.getPageNumber(), queryParam.getPageSize(), renewalModel);
        IPage<JournalRenewalDO> pageData = journalRenewalService.findPageList(queryModel);
        List<JournalRenewalPageVO> list = CollectionUtil.isEmpty(pageData.getRecords()) ? null :
                pageData.getRecords().stream().map(item -> {
                    JournalRenewalPageVO journalRenewalPageVO = CustomBeanUtil.copyProperties(item, new JournalRenewalPageVO());
                    journalRenewalPageVO.setTargetClazzPrice(NumberUtil.convertToYuan(item.getTargetClazzPrice()));
                    return journalRenewalPageVO;
                }).toList();
        return ResponseEntity.ok().body(Page.of(queryModel.getPageNumber(), queryModel.getPageSize(), Long.valueOf(pageData.getTotal()).intValue(), list));
    }

    /**
     * 根据 ID查询详情
     *
     * @param id 升级凭单ID
     * @return 详情实体
     */
    @GetMapping("/{id}")
    public ResponseEntity<JournalRenewalDTO> detail(@PathVariable("id") String id) {
        JournalRenewalDTO renewalDTO = journalRenewalService.findById(id);
//        Assert.isFalse(!AccountHolder.hasEmployeeGroups(renewalDTO.getTargetClazzCampusId(), renewalDTO.getTargetClazzSubjectId()), BizExceptionProducer.unauthorized("暂无权限"));
        return ResponseEntity.ok().body(renewalDTO);
    }

    /**
     * 根据 ID删除 升级凭单
     *
     * @param id 升级凭单ID
     * @return 详情实体
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable("id") String id) {
        journalRenewalService.deleteById(id);
        ;
        return ResponseEntity.ok().body(true);
    }


    /**
     * 根据学籍ID查询优惠列表
     *
     * @param recordId 学籍ID
     * @return 优惠项列表
     */
    @GetMapping("/{renewal_id}/{record_id}/discounts")
    public ResponseEntity<?> findDiscountsByRenewalIdAndRecordId(@PathVariable("renewal_id") String renewalId, @PathVariable("record_id") String recordId) {
        List<JournalRenewalLineDiscountDO> discounts = journalRenewalService.findDiscountsByRenewalIdAndRecordId(renewalId, recordId);
        List<StudentRecordDiscountsVO> list = null;
        if (CollectionUtil.isNotEmpty(discounts)) {
            list = discounts.stream().map(item -> {
                StudentRecordDiscountsVO discountsVO = CustomBeanUtil.copyProperties(item, new StudentRecordDiscountsVO());
                discountsVO.setDiscountAmount(NumberUtil.convertToYuan(item.getDiscountAmount()));
                return discountsVO;
            }).toList();
        }
        return ResponseEntity.ok().body(list);
    }

    /**
     * 新建凭单
     *
     * @param editVO 表单对象
     * @return 是否成功
     **/
    @PutMapping
    public ResponseEntity<JournalRenewalDTO> create(@RequestBody @Validated JournalRenewalEditVO editVO) {
        log.info("[保存升级凭单草稿] 请求参数: {}", JSON.toJSONString(editVO));
        JournalRenewalWebUtil.validateCreateRequestParam(editVO);
        JournalRenewalDTO renewalDTO = JournalRenewalWebUtil.transferJournalRenewalDTO(editVO);
        renewalDTO.setLineList(JournalRenewalWebUtil.transferJournalRenewalLineDTO(editVO));
        return ResponseEntity.ok(journalRenewalService.create(renewalDTO));
    }

    /**
     * 提交升级凭单
     *
     * @param editVO 表单对象
     * @return 是否成功
     **/
    @PutMapping("/flow")
    public ResponseEntity<JournalRenewalDTO> flow(@RequestBody @Validated JournalRenewalEditVO editVO) {
        log.info("[提交升级凭单草稿] 请求参数: {}", JSON.toJSONString(editVO));
        JournalRenewalWebUtil.validateCreateRequestParam(editVO);
        JournalRenewalDTO renewalDTO = JournalRenewalWebUtil.transferJournalRenewalDTO(editVO);
        renewalDTO.setLineList(JournalRenewalWebUtil.transferJournalRenewalLineDTO(editVO));
        Assert.notEmpty(editVO.getLineList(), BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY, "学生列表"));
        return ResponseEntity.ok(journalRenewalService.flow(renewalDTO));
    }

    /**
     * 提交
     *
     * @param id 升级凭单ID
     * @return 是否成功
     **/
    @PutMapping("/flow/{id}")
    public ResponseEntity<JournalRenewalDTO> flow(@PathVariable("id") String id) {
        log.info("[提交升级凭单] 请求参数: {}", JSON.toJSONString(id));
        JournalRenewalDTO renewalDTO    = journalRenewalService.flow(id);
        return ResponseEntity.ok(renewalDTO);
    }

}
